#!/usr/bin/env python

import sys,os
import getopt
import re


#usage dns.py -f filename -d forward_ip [-p 53]

def usage():
    print "usage:"
    print sys.argv[0], "-f filename -d forward_ip [-p 53]"
    sys.exit()

def process_domain(domain):
    domain=domain.strip("\r\n")
    if domain[-1] !=".":
        domain+="."
    if domain[0] != "@":
        c=re.search("[^.]+\.([^.]+\.[^.]+\.$)",domain)
        if c:
            domain=c.group(1)
    else:
        domain=domain[1:]
    return domain



def main():
    fpath=""
    dip=""
    port="53"
    try:
        opts, args = getopt.getopt(sys.argv[1:],"f:d:p:")
    except getopt.error, msg:
        print msg
        usage()
    for i in opts:
        if i[0] == "-f":
            fpath=i[1]
            w=os.path.isfile(fpath)
            if not w:
                print "ERROR! %s is not existing!"%fpath
                usage()
        elif i[0] == "-d":
            dip=i[1]
            c=re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",dip)
            if not c:
                print "ERROR! wrong FORWARD ip format."
                usage()
        else:
            port=i[0]
    if fpath=="" or dip=="" :
        print "ERROR! need more argv!"
        usage()
#zone "bdwm.net." {
#	type forward;
#	forwarders {
#		166.111.8.28;
#	};
#};
    for line in open(fpath):
        line=line.strip("\r\n")
        if line[0]=="#" or line=="":
            continue;
        else:
            line=process_domain(line)
        print "\
zone \"%s\" { \n\
    type forward;\n\
    forwarders { \n\
        %s;\n\
    };\n\
};\n\n"%(line,dip)
        


if __name__ == "__main__":
     main()
